package org.nmgyjt.springboot.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.nimbusds.jose.JOSEException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.nmgyjt.springboot.beans.admin.*;
import org.nmgyjt.springboot.beans.dto.LoginBean;
import org.nmgyjt.springboot.entity.ApiCodeEnum;
import org.nmgyjt.springboot.entity.ApiRes;
import org.nmgyjt.springboot.entity.admin.CsBusiness;
import org.nmgyjt.springboot.entity.admin.CsBusinessUserAuth;
import org.nmgyjt.springboot.entity.admin.CsSystemAdmin;
import org.nmgyjt.springboot.entity.admin.UserInfo;
import org.nmgyjt.springboot.entity.login.LoginUserVO;
import org.nmgyjt.springboot.entity.login.LoginVO;
import org.nmgyjt.springboot.entity.sms.YuFuMSSendEntity;
import org.nmgyjt.springboot.service.ICsBusinessService;
import org.nmgyjt.springboot.service.ICsSystemAdminService;
import org.nmgyjt.springboot.service.impl.SendSMSServiceImpl;
import org.nmgyjt.springboot.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;
import java.text.ParseException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/cs/ad")
@CrossOrigin
@Slf4j
public class CsSystemAdminController {

    @Autowired
    private ICsSystemAdminService service;

    @Autowired
    private TokenUtil tokenUtil;

    @Autowired
    SendSMSServiceImpl smsService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private PropertiesUtil propertiesUtil;

    @Autowired
    private ICsBusinessService iCsBusinessService;

    /**
     * 登陆成功后,获取自身管理员权限
     *
     * @param bean
     * @return
     */
    @PostMapping("/myself")
    public ApiRes getOne(@RequestBody CsSystemAdminListSelectBean bean) {
        List<CsSystemAdmin> admin = service.list(new LambdaQueryWrapper<CsSystemAdmin>()
                .eq(CsSystemAdmin::getPhone, bean.getPhone())
                .eq(CsSystemAdmin::getOrgId, bean.getOrgId()));
        if (CollectionUtils.isEmpty(admin)) {
            log.error("获取管理员权限失败,管理员权限还未配置");
            return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_NO_PERMISSION);
        }
        return ApiRes.ok(admin);
    }

    @PostMapping("/exist")
    public ApiRes exist(@RequestBody CsSystemAdminListSelectBean bean) {
        List<CsSystemAdmin> admin = service.list(new LambdaQueryWrapper<CsSystemAdmin>()
                .eq(CsSystemAdmin::getPhone, bean.getPhone()));
        if (CollectionUtils.isEmpty(admin)) {
            return ApiRes.ok();
        }
        return ApiRes.ok(admin);
    }

    @PostMapping("/code")
    public ApiRes checkCode(@RequestBody @Validated CsSystemLoginCodeBean bean) throws ParseException, JOSEException {

        UserInfo userInfo = IDAASUserUtils.selectUserInfoFromIDAASByOpenIdV2(bean.getMobile());
        if (ObjectUtils.isEmpty(userInfo)) {
            log.error("手机号为:{}的管理员账号不存在,发送验证码失败", bean.getMobile());
            return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_ADMIN_PHONE_WRONG);
        }
        CsSystemAdmin admin = service.getOne(new LambdaQueryWrapper<CsSystemAdmin>().eq(CsSystemAdmin::getPhone, bean.getCreatedBy()).eq(CsSystemAdmin::getOrgId, bean.getOrgId()).orderByDesc(CsSystemAdmin::getUpdatedTime).last("limit 1"));
        if (ObjectUtils.isEmpty(admin)) {
            log.error("管理员权限为空", bean.getMobile());
            return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_NO_PERMISSION);
        }
        YuFuMSSendEntity sendEntity = new YuFuMSSendEntity();
        String numbers = RandomUtil.randomNumbers(6);
        List<String> params = new ArrayList<>();
        List<String> phone = new ArrayList<>();
        phone.add(userInfo.getValues().getUsername());

        params.add(userInfo.getValues().getDisplayName());
        params.add(admin.getOrgName());
        params.add(admin.getName());
        params.add(admin.getPhone());
        params.add(bean.getOrgName());
        params.add(numbers);
        sendEntity.setType("user.check");
        sendEntity.setPhoneNumSet(phone);
        sendEntity.setTemplateParamSet(params);
        smsService.sendMS(sendEntity);
        redisUtil.set("nmgyjt_cs_" + bean.getMobile(), numbers);
        return ApiRes.ok();
    }

    @PostMapping("/check")
    public ApiRes checkCode(@RequestBody @Validated CsSystemCodeLoginBean bean) {


        String code = redisUtil.get("nmgyjt_cs_" + bean.getMobile());
        if (code.equals(bean.getCode())) {
            List<CsSystemAdmin> admin = service.list(new LambdaQueryWrapper<CsSystemAdmin>()
                    .eq(CsSystemAdmin::getPhone, bean.getMobile()));
            return ApiRes.ok(admin);
        } else {
            return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_ADMIN_CODE_WRONG);
        }
    }

    @GetMapping("/idaas_login")
    public ApiRes idaasLongin() {
        String idaasUrl = "http://idaas-idp.nmgyjtwg.org.cn/sso/tn-3f90f739227e498bb3505237e6c397bb/ai-709f95137b5b4c4eb1613fc3e94131db/oidc/authorize?response_type=code&client_id=ai-709f95137b5b4c4eb1613fc3e94131db&redirect_uri=http://58.18.173.228:90/cs/ad/idaas/callbackDemo&scope=openid%20offline_access";
        HashMap<String, String> headerParams = new HashMap<>();
        String httpGet = HttpUtils.httpGet("idaasUrl", new HashMap(), headerParams);

        return ApiRes.ok();
    }

    @PostMapping("/login/nesting")
    public ApiRes nestingLogin(@RequestBody @Validated LoginBean bean) throws Exception {

        QueryWrapper<CsBusiness> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("business_id", bean.getBusinessId());

        List<CsBusiness> csBusinessList = iCsBusinessService.list(queryWrapper);
        if (CollUtil.isEmpty(csBusinessList)) {
            log.error("业务系统不存在,登录失败!");
            return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_PWD_WRONG);
        }
        log.info("nestingLogin:{}  salt:{}", JSONUtil.toJsonStr(bean) ,csBusinessList.get(0).getSalt());
        Map<String, Object>  json =  JsonDataSecurity.decryptAndParseJsonData(bean.getCiphertext(), csBusinessList.get(0).getSalt());
        log.info("nestingLogin-json:{}",json);
        String username = (String) json.get("username");
        String password = (String) json.get("password");
        if ("nmgYjt@123456".equals(password)) {
            CsSystemAdminPwdBean pwdBean = new CsSystemAdminPwdBean();
            pwdBean.setPassword(password);
            pwdBean.setUsername(username);
            List<CsSystemAdmin> admin = service.login(pwdBean);
            if (CollectionUtils.isEmpty(admin)) {
                log.error("登录账户名/密码错误,登录失败!");
                return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_PWD_WRONG);
            }
            return ApiRes.ok(admin);
        }
        return ApiRes.ok();

    }


    @PostMapping("/login/pwd")
    public ApiRes pwdLongin(@RequestBody @Validated CsSystemAdminPwdBean bean) throws ParseException, JOSEException {

        HashMap<String, String> headerParams = new HashMap<>();
        headerParams.put("Content-Type", "application/json");

        if ("nmgYjt@123456".equals(bean.getPassword())) {
            List<CsSystemAdmin> admin = service.login(bean);
            if (CollectionUtils.isEmpty(admin)) {
                log.error("登录账户名/密码错误,登录失败!");
                return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_PWD_WRONG);
            }
            return ApiRes.ok(admin);
        } else {
            String url1 = "http://idaas-idp.nmgyjtwg.org.cn/api/v1/idaas-idp.nmgyjtwg.org.cn/login";
            String loginStr = HttpUtils.sendHttpPost(url1, (JSONObject) JSON.toJSON(bean), headerParams);
            log.info(loginStr);
            if (StringUtils.isNotEmpty(loginStr)) {
                CsSystemAdminActivateBean activateBean = JSONObject.parseObject(loginStr, CsSystemAdminActivateBean.class);
                String url2 = "";
                if (activateBean.getErrorCode() == 200001008 || activateBean.getErrorCode() == 200001006) {
                    if (activateBean.getErrorCode() == 200001008)
                        url2 = "http://idaas-idp.nmgyjtwg.org.cn/api/v1/idaas-idp.nmgyjtwg.org.cn/activate_self?token=" + activateBean.getDetails().getToken();
                    if (activateBean.getErrorCode() == 200001006)
                        url2 = "http://idaas-idp.nmgyjtwg.org.cn/api/v1/idaas-idp.nmgyjtwg.org.cn/set_password?token=" + activateBean.getDetails().getToken();
                    Map params = new HashMap<>();
                    params.put("password", bean.getPassword());
                    params.put("qas", new ArrayList<>());

                    headerParams.put("token", activateBean.getDetails().getToken());

                    String loginStr2 = HttpUtils.sendHttpPost(url2, (JSONObject) JSON.toJSON(params), headerParams);
                    if (StringUtils.isEmpty(loginStr2)) {
                        List<CsSystemAdmin> admins = service.login(bean);
                        if (ObjectUtils.isEmpty(admins)) {
                            log.error("获取管理员权限失败,管理员权限还未配置");
                            return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_NO_PERMISSION);
                        }
                        return ApiRes.ok(admins);
                    } else {
                        return ApiRes.fail(401, "登录密码错误");
                    }
                } else {

                    log.error("登录账户名/密码错误,登录失败!");
                    return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_PWD_WRONG);
                }
            } else {
                List<CsSystemAdmin> admins = service.login(bean);
                if (ObjectUtils.isEmpty(admins)) {
                    log.error("获取管理员权限失败,管理员权限还未配置");
                    return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_NO_PERMISSION);
                }
                return ApiRes.ok(admins);
            }
        }
    }


    @PostMapping("/reset")
    public ApiRes reset(@RequestBody @Validated CsSystemAdminResetBean bean) throws ParseException, JOSEException {
        String regex = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d).{7,17}$";
        //^(?=.[a-z])(?=.[A-Z])(?=.*\d)(?=.*\W)[^]{6,16}$
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(bean.getPassword());
        if (matcher.matches()) {
            HashMap<String, String> headerParams = new HashMap<>();
            headerParams.put("Content-Type", "application/json");
            headerParams.put("Authorization", "bearer " + NMGYJTIDAASTokenUtils.getToken());

            UserInfo userInfo = IDAASUserUtils.selectUserInfoFromIDAASByOpenIdV2(bean.getUsername());
            if (null != userInfo && StringUtils.isNotEmpty(userInfo.getId())) {

                HashMap<String, String> headerParams2 = new HashMap<>();
                headerParams2.put("Content-Type", "application/json");
                String url1 = "http://idaas-admin.nmgyjtwg.org.cn/api/v1/tn-3f90f739227e498bb3505237e6c397bb/objects/" + userInfo.getId() + "/reset_password";

                Map restBean = new HashMap<>();
                restBean.put("password", "nmgYjt@123456");
                restBean.put("scriptContent", "");
                restBean.put("script", false);
                String resetStr = HttpUtils.sendHttpPost(url1, (JSONObject) JSON.toJSON(restBean), headerParams);
                UserInfo userResponse = JSONObject.parseObject(resetStr, UserInfo.class);
                if (null != userResponse && StringUtils.isNotEmpty(userResponse.getId())) {
                    String url2 = "http://idaas-idp.nmgyjtwg.org.cn/api/v1/idaas-idp.nmgyjtwg.org.cn/login";
                    CsSystemAdminPwdBean pwdBean = new CsSystemAdminPwdBean();
                    pwdBean.setUsername(bean.getUsername());
                    pwdBean.setPassword("nmgYjt@123456");
                    String loginStr = HttpUtils.sendHttpPost(url2, (JSONObject) JSON.toJSON(pwdBean), headerParams2);
                    log.info("loginStr\n" + loginStr);
                    if (StringUtils.isNotEmpty(loginStr)) {
                        CsSystemAdminActivateBean activateBean = JSONObject.parseObject(loginStr, CsSystemAdminActivateBean.class);
                        if (null != activateBean && null != activateBean.getDetails() && StringUtils.isNotEmpty(activateBean.getDetails().getToken())) {

                            String url3 = "http://idaas-idp.nmgyjtwg.org.cn/api/v1/idaas-idp.nmgyjtwg.org.cn/set_password?token=" + activateBean.getDetails().getToken();
                            Map params = new HashMap<>();
                            params.put("password", bean.getPassword());
                            headerParams2.put("token", activateBean.getDetails().getToken());
                            String loginStr2 = HttpUtils.sendHttpPost(url3, (JSONObject) JSON.toJSON(params), headerParams2);
                            log.info("loginStr2\n" + loginStr2);
                            if (StringUtils.isEmpty(loginStr2)) {
                                return ApiRes.ok();
                            }
                        }
                    }
                }
            }
            return ApiRes.fail(500, "修改密码失败,请稍后再试/联系系统管理员!");
        } else {
            return ApiRes.fail(403, "修改密码失败,密码设定要求规则如下:" + "\n1.位数介于7~16 位之间;" + "\n2.必须包含大写字母;" + "\n3.建议包含一个特殊字符或下划线;");
        }
    }

    @PostMapping("/login/code")
    public ApiRes codeLogin(@RequestBody @Validated CsSystemCodeLoginBean bean) throws
            ParseException, JOSEException {

        HashMap<String, String> headerParams = new HashMap<>();
        headerParams.put("Content-Type", "application/json");

        String url1 = "http://idaas-idp.nmgyjtwg.org.cn/api/v1/idaas-idp.nmgyjtwg.org.cn/login/sms";
        bean.setMobile("+86-" + bean.getMobile());
        String loginStr = HttpUtils.sendHttpPost(url1, (JSONObject) JSON.toJSON(bean), headerParams);
        log.info(loginStr);
        if (StringUtils.isEmpty(loginStr)) {
            CsSystemAdminPwdBean adminPwdBean = new CsSystemAdminPwdBean();
            adminPwdBean.setUsername(bean.getMobile());
            adminPwdBean.setPassword(bean.getCode());
            List<CsSystemAdmin> admins = service.login(adminPwdBean);
            if (CollectionUtils.isEmpty(admins)) {
                log.error("获取管理员权限失败,管理员权限还未配置");
                return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_NO_PERMISSION);
            }
            return ApiRes.ok(admins);
        } else {
            return ApiRes.fail(401, "登录密码错误");
        }
    }


    @PostMapping("/login/smsotp")
    public ApiRes smsotp(@RequestBody @Validated CsSystemLoginCodeBean bean) throws ParseException, JOSEException {

        HashMap<String, String> headerParams = new HashMap<>();
        headerParams.put("Content-Type", "application/json");

        String url1 = "http://idaas-idp.nmgyjtwg.org.cn/api/v1/idaas-idp.nmgyjtwg.org.cn/login/smsotp";
        bean.setMobile("+86-" + bean.getMobile());
        HttpUtils.sendHttpPost(url1, (JSONObject) JSON.toJSON(bean), headerParams);
        return ApiRes.ok();
    }

    @PostMapping("/update_password")
    public ApiRes callback(@RequestBody @Validated CsSystemAdminPasswordModifyBean pw) throws
            ParseException, JOSEException {

        String url = "http://idaas.nmgyjtwg.org.cn/api/v1/tn-3f90f739227e498bb3505237e6c397bb/self/update_password";

        HashMap<String, String> headerParams = new HashMap<>();
        headerParams.put("Content-Type", "application/json");
        headerParams.put("Authorization", "bearer " + NMGYJTIDAASTokenUtils.getToken());

        return ApiRes.ok(HttpUtils.sendHttpPost(url,
                (JSONObject) JSON.toJSON(pw), headerParams));
    }

    @GetMapping("/idaas/callbackDemo")
    public ApiRes callbackGet( @RequestParam String code) throws ParseException, JOSEException {
        log.info("callbackGet->{}",code);
        if (StringUtils.isEmpty(code)) {
            log.error("认证失败,统一认证返回参数code 为空!");
            return ApiRes.fail(401, "登陆失败,统一认证不通过!");
        } else {
            HashMap<String, String> headerParams = new HashMap<>();
            JSONObject bodyParams = new JSONObject();
            headerParams.put("Content-Type", "application/json");
            String str64 = propertiesUtil.propLoad("spring.nmgyjt.login.idaas.client_id") + ":"
                    + propertiesUtil.propLoad("spring.nmgyjt.login.idaas.client_secret");
            String encodeData = BaseSixtyFourUtil.encodeData(str64);
            headerParams.put("Authorization", "Basic " + encodeData);

            bodyParams.put("grant_type", "authorization_code");
            bodyParams.put("code", code );
            bodyParams.put("redirect_uri", propertiesUtil.propLoad("spring.nmgyjt.login.idaas.redirect_uri"));

            String clientPostRes = HttpUtils.sendHttpPost(
                    propertiesUtil.propLoad("spring.nmgyjt.login.idaas.token_endpoint"),
                    (JSONObject) JSON.toJSON(bodyParams), headerParams);
            log.info("clientPostRes:{}",clientPostRes);
            if (null != clientPostRes && clientPostRes.contains("access_token")) {
                LoginVO loginVO = JSONObject.parseObject(clientPostRes, LoginVO.class);
                headerParams.clear();
                headerParams.put("Content-Type", "application/json");
                headerParams.put("Authorization", "Bearer " + loginVO.getAccess_token());
                String httpGet = HttpUtils.httpGet(propertiesUtil.propLoad("spring.nmgyjt.login.idaas.userinfo_endpoint"), new HashMap(), headerParams);
                log.info("httpGet:{}",httpGet);
                if (null != httpGet) {
                    LoginUserVO userVO = JSONObject.parseObject(httpGet, LoginUserVO.class);

                    CsSystemAdminPwdBean adminLoginBean = new CsSystemAdminPwdBean();
                    adminLoginBean.setUsername(userVO.getPhone_number());
                    List<CsSystemAdmin> admins = service.login(adminLoginBean);

                    if (CollectionUtils.isEmpty(admins))
                        return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_NO_PERMISSION);

                    return ApiRes.ok(admins);
                }

            }
        }
        return ApiRes.fail(401, "登录失败,密码错误/用户没有登陆权限!");
    }

    @PostMapping("/idaas/callback")
    public ApiRes callback(@RequestBody CsSystemAdminIdaasLoginBean bean) throws ParseException, JOSEException {
        log.info("callback->{}",bean.getCode());
        if (StringUtils.isEmpty(bean.getCode())) {
            log.error("认证失败,统一认证返回参数code 为空!");
            return ApiRes.fail(401, "登陆失败,统一认证不通过!");
        } else {
            HashMap<String, String> headerParams = new HashMap<>();
            JSONObject bodyParams = new JSONObject();
            headerParams.put("Content-Type", "application/json");
            String str64 = propertiesUtil.propLoad("spring.nmgyjt.login.idaas.client_id") + ":"
                    + propertiesUtil.propLoad("spring.nmgyjt.login.idaas.client_secret");
            String encodeData = BaseSixtyFourUtil.encodeData(str64);
            headerParams.put("Authorization", "Basic " + encodeData);

            bodyParams.put("grant_type", "authorization_code");
            bodyParams.put("code", bean.getCode());
            bodyParams.put("redirect_uri", propertiesUtil.propLoad("spring.nmgyjt.login.idaas.redirect_uri"));

            String clientPostRes = HttpUtils.sendHttpPost(
                    propertiesUtil.propLoad("spring.nmgyjt.login.idaas.token_endpoint"),
                    (JSONObject) JSON.toJSON(bodyParams), headerParams);


            if (null != clientPostRes && clientPostRes.contains("access_token")) {
                LoginVO loginVO = JSONObject.parseObject(clientPostRes, LoginVO.class);
                headerParams.clear();
                headerParams.put("Content-Type", "application/json");
                headerParams.put("Authorization", "Bearer " + loginVO.getAccess_token());
                String httpGet = HttpUtils.httpGet(propertiesUtil.propLoad("spring.nmgyjt.login.idaas.userinfo_endpoint"), new HashMap(), headerParams);


                if (null != httpGet) {
                    LoginUserVO userVO = JSONObject.parseObject(httpGet, LoginUserVO.class);

                    CsSystemAdminPwdBean adminLoginBean = new CsSystemAdminPwdBean();
                    adminLoginBean.setUsername(userVO.getPhone_number());
                    List<CsSystemAdmin> admins = service.login(adminLoginBean);

                    if (CollectionUtils.isEmpty(admins))
                        return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_NO_PERMISSION);

                    return ApiRes.ok(admins);
                }

            }
        }
        return ApiRes.fail(401, "登录失败,密码错误/用户没有登陆权限!");
    }

    /**
     * 获取相关菜单的管理员列表
     *
     * @param bean
     * @return
     */
    @PostMapping("/list")
    public ApiRes getList(@RequestBody CsSystemAdminSelectBean bean) {

        if ("1000000001".equals(bean.getMenuID()) || "党委管理员".equals(bean.getMenuName())) {
            bean.setOrgName("党委领导");
        } else if ("1000000002".equals(bean.getMenuID()) || "政府管理员".equals(bean.getMenuName())) {
            bean.setOrgName("政府领导");
        }

        //CsSystemAdmin admin = service.getOne(new LambdaQueryWrapper<CsSystemAdmin>().eq(CsSystemAdmin::getPhone, bean.getCreatedBy()));
        //.eq(CsSystemAdmin::getSuperiorOrg, bean.getOrgId()));
        return ApiRes.ok(service.list(
                new LambdaQueryWrapper<CsSystemAdmin>()
                        //.eq(CsSystemAdmin::getAreaCode, admin.getAreaCode())
                        //.eq(CsSystemAdmin::getOrgName, bean.getOrgName())
                        //.eq(CsSystemAdmin::getOffice, bean.getOffice())
                        .eq(CsSystemAdmin::getStatus, 1)
                        //.eq(CsSystemAdmin::getJob, bean.getJob())
                        .eq(CsSystemAdmin::getSuperiorOrg, bean.getOrgId())
                        .eq(CsSystemAdmin::getMenuId, bean.getMenuID())
                        // .eq(CsSystemAdmin::ge, bean.getCreatedBy())
                        .orderByAsc(CsSystemAdmin::getUdOrder)
                        .orderByDesc(CsSystemAdmin::getOrgName).orderBy(true, false, CsSystemAdmin::getUpdatedBy).last("limit 1")));
    }


    @PostMapping("/new")
    public ApiRes createAdmin(@RequestBody @Validated CsSystemAdminCreateBean bean,HttpServletRequest request) throws
            ParseException, JOSEException {

        String ipAddress;
        // 如果存在X-Forwarded-For，则优先取该头信息中的IP地址
        String xForwardedFor = request.getHeader("X-Forwarded-For");
        if (xForwardedFor != null && !xForwardedFor.isEmpty()) {
            ipAddress = xForwardedFor.split(",")[0];
        } else {
            // 否则使用request.getRemoteAddr()作为备选方案
            ipAddress = request.getRemoteAddr();
        }
        log.info("Client IP address:{} " , ipAddress); ;
        bean.setIp(ipAddress);

//        if ("1000000010".equals(bean.getMenuID()) && StringUtils.isNotEmpty(bean.getOrgName())
//                && ( null == bean.getMajorDuties() || StringUtils.isEmpty(bean.getMajorDuties()) || "[]".equals(bean.getMajorDuties()) )) {
//            log.error("救援队伍的主要救援能力不允许为空,救援队伍创建失败!,创建信息如下:\n{}", bean);
//            return ApiRes.fail(400, "救援队伍的主要救援能力不允许为空,救援队伍创建失败!");
//        }

        if ("1000000010".equals(bean.getMenuID()) && StringUtils.isNotEmpty(bean.getOrgName()) && (null == bean.getSecondaryDuties() || StringUtils.isEmpty(bean.getSecondaryDuties()))) {
            log.error("救援队伍的辅助救援能力不允许为空,救援队伍创建失败!,创建信息如下:\n{}", bean);
            return ApiRes.fail(400, "救援队伍的辅助救援能力不允许为空,如没有具体辅助救援能力请选择\"无\"!");
        }

        if ("1000000006".equals(bean.getMenuID()) && !ObjectUtils.isEmpty(bean.getPreSetOrgInfos())) {
            if (JSONObject.toJSONString(bean.getPreSetOrgInfos()).contains("1000000012")) {
                for (CsSystemOrgPreSetBean be : bean.getPreSetOrgInfos()) {
                    if ("1000000012".equals(be.getId()) && CollectionUtils.isEmpty(be.getChildren())) {
                        log.error("防护目标的预设类型选择为空,创建失败!,创建信息如下:\n{}", bean);
                        return ApiRes.fail(400, "防护目标的预设类型不允许为空!");
                    }
                }
            }
        }

        if (StringUtils.isEmpty(bean.getPhone())) {
            log.error("创建管理员记录失败,手机号码为空");
            return ApiRes.fail(400, "创建管理员记录失败,管理员手机号码不允许为空");
        }
        UserInfo adminUserInfo = IDAASUserUtils.selectUserInfoFromIDAASByOpenIdV2(bean.getCreatedBy());
        if (ObjectUtils.isEmpty(adminUserInfo)) {
            log.error("创建统一认证用户的管理员账号非法,创建失败,创建信息如下:{}", bean);
            return ApiRes.fail(401, "创建统一认证用户的管理员账号非法,创建失败");
        }


        if (StringUtils.isEmpty(bean.getOrgName())) {
            bean.setOrgName(bean.getWorkUnit());
        }

        String admin = service.createCsSystemAdmin(bean, adminUserInfo);
        if (null == admin) {
            return ApiRes.fail(500, "系统异常,创建管理员失败");
        } else {
            if (admin.contains("预设总数")) {
                return ApiRes.fail(400, admin);
            }
            return ApiRes.ok(admin);
        }

    }

    @PostMapping("/order")
    public ApiRes udOrderAdmin(@RequestBody @Validated CsSystemAdminCreateBean bean) throws
            ParseException, JOSEException {

        UserInfo adminUserInfo = IDAASUserUtils.selectUserInfoFromIDAASByOpenIdV2(bean.getCreatedBy());
        if (ObjectUtils.isEmpty(adminUserInfo)) {
            log.error("更新用户的管理员账号非法,更新失败,创建信息如下:{}", bean);
            return ApiRes.fail(401, "更新户的管理员账号非法,更新失败");
        }
        service.createCsSystemAdmin(bean, adminUserInfo);
        return ApiRes.ok();
    }


    @PostMapping("/update")
    public ApiRes updateAdmin(@RequestBody CsSystemAdminCreateBean bean,HttpServletRequest request) throws ParseException, JOSEException {

//        if ("1000000010".equals(bean.getMenuID()) && (null == bean.getMajorDuties()
//                || StringUtils.isEmpty(bean.getMajorDuties())
//                || "[]".equals(bean.getMajorDuties()) )) {
//            log.error("救援队伍的主要救援能力不允许为空,救援队伍创建失败!,创建信息如下:\n{}", bean);
//            return ApiRes.fail(400, "救援队伍的主要救援能力不允许为空,救援队伍创建失败!");
//        }

        if ("1000000010".equals(bean.getMenuID()) && (null == bean.getSecondaryDuties() || StringUtils.isEmpty(bean.getSecondaryDuties()))) {
            log.error("救援队伍的辅助救援能力不允许为空,救援队伍创建失败!,创建信息如下:\n{}", bean);
            return ApiRes.fail(400, "救援队伍的辅助救援能力不允许为空,如没有具体辅助救援能力请选择\"无\"!");
        }

        if ("1000000006".equals(bean.getMenuID()) && !ObjectUtils.isEmpty(bean.getPreSetOrgInfos())) {
            if (JSONObject.toJSONString(bean.getPreSetOrgInfos()).contains("1000000012")) {
                for (CsSystemOrgPreSetBean be : bean.getPreSetOrgInfos()) {
                    if ("1000000012".equals(be.getId()) && CollectionUtils.isEmpty(be.getChildren())) {
                        log.error("防护目标的预设类型选择为空,创建失败!,创建信息如下:\n{}", bean);
                        return ApiRes.fail(400, "防护目标的预设类型不允许为空!");
                    }
                }
            }
        }

        CsSystemAdmin admin = service.getById(bean.getId());
        if (null == admin || StringUtils.isEmpty(admin.getId())) {
            log.error("更新管理员记录失败,手机号码为空");
            return ApiRes.fail(401, "更新管理员记录不存在,更新失败!");
        }
        if (StringUtils.isEmpty(bean.getPhone())) {
            log.error("更新管理员记录失败,手机号码为空");
            return ApiRes.fail(400, "更新管理员记录失败,管理员手机号码不允许为空");
        }

        UserInfo adminUserInfo = IDAASUserUtils.selectUserInfoFromIDAASByOpenIdV2(bean.getCreatedBy());

      /*  UserInfo userInfo = IDAASUserUtils.selectUserInfoFromIDAASByOpenId(bean.getPhone());

        if (null != userInfo) {
            log.error("更新用户的管理员账号失败,更新信息如下:{}", bean);
            return ApiRes.fail(401, "更新户的管理员失败,手机号码已经注册,请重新核对!/联系系统管理员处理!");
        }*/

        String ipAddress;
        // 如果存在X-Forwarded-For，则优先取该头信息中的IP地址
        String xForwardedFor = request.getHeader("X-Forwarded-For");
        if (xForwardedFor != null && !xForwardedFor.isEmpty()) {
            ipAddress = xForwardedFor.split(",")[0];
        } else {
            // 否则使用request.getRemoteAddr()作为备选方案
            ipAddress = request.getRemoteAddr();
        }
        log.info("Client IP address:{} " , ipAddress); ;
        bean.setIp(ipAddress);

        return ApiRes.ok(service.updateCsSystemAdmin(bean, adminUserInfo));
    }

    @PostMapping("/menu")
    public ApiRes addMenu(@RequestBody CsSystemMenuUpdateBean bean) {

        CsSystemAdmin admin = service.getOne(CsSystemAdmin.gw().eq(CsSystemAdmin::getPhone, bean.getCreatedBy()));
        if (ObjectUtils.isEmpty(admin)) {
            log.error("查询管理员记录失败");
            return ApiRes.fail(400, "记录 ID 错误,管理员记录为空");
        }

        List<String> list = Arrays.asList(StringUtils.split(admin.getMenuPermission(), ":"));
        if (list.size() <= 2) {
            admin.setMenuPermission(list.get(0) + ":" + bean.getMenuIds() + ":");
        } else {
            admin.setMenuPermission(list.get(0) + ":" + bean.getMenuIds() + ":" + list.get(2));
        }
        service.saveOrUpdate(admin);
        return ApiRes.ok();
    }


    // @PostMapping("/area")
    public ApiRes area() throws ParseException, JOSEException {

        HashMap<String, String> headerParams = new HashMap<>();
        headerParams.put("Content-Type", "application/json");
        headerParams.put("Authorization", "Bearer " + NMGYJTIDAASTokenUtils.getToken());

        /*{
            "values":{
            "name":"内蒙古", "code":"150000000", "parentId":"", "status":"PENDING_ACTIVE"
        }
        }*/
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> params = new HashMap<>();
        params.put("name", "内蒙古自治区");
        params.put("code", "150000000");
        params.put("parentId", "");
        params.put("status", "PENDING_ACTIVE");
        params.put("hasChild", true);
        map.put("values", params);
        /*IDAASAreaEntity idaasArea = new IDAASAreaEntity();
        IDAASAreaValuesEntity valuesEntity = new IDAASAreaValuesEntity();
        valuesEntity.setName("内蒙古自治区");
        valuesEntity.setCode("150000000");
        valuesEntity.setHasChild(true);
        idaasArea.setValues(valuesEntity);
        idaasArea.setObjectType("AREA");*/

        String areaPostRes = HttpUtils.sendHttpPut("http://idaas-admin.nmgyjtwg.org.cn/api/v1/tn-3f90f739227e498bb3505237e6c397bb/objects/ob-3217938a528f4e5a9d5d3b538fecd786", (JSONObject) JSON.toJSON(map), headerParams);
        log.info(areaPostRes);

        return ApiRes.ok();
    }


}
